package org.finesys.common.security.authentication.handler;

import org.finesys.common.core.util.WebUtils;
import org.finesys.system.api.entity.SysLog;
import org.finesys.system.api.feign.LogServiceApi;
import org.springframework.context.ApplicationListener;
import org.springframework.http.HttpHeaders;
import org.springframework.lang.NonNull;
import org.springframework.security.authentication.event.LogoutSuccessEvent;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken;

import cn.hutool.extra.servlet.ServletUtil;
import cn.hutool.extra.spring.SpringUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * 事件机制处理退出相关
 */
@Slf4j
public class AuthLogoutSuccessEventHandler implements ApplicationListener<LogoutSuccessEvent> {

    @Override
    public void onApplicationEvent(@NonNull LogoutSuccessEvent event) {
        Authentication authentication = (Authentication) event.getSource();
        if (authentication instanceof PreAuthenticatedAuthenticationToken) {
            handle(authentication);
        }
    }

    /**
     * 登出成功
     */
    public void handle(Authentication authentication) {
        if (log.isInfoEnabled()) {
            log.info("用户：{} 退出成功", authentication.getPrincipal());
        }
        SysLog logDto = new SysLog();
        logDto.setTitle(String.format("用户[%s]退出成功", authentication.getName()));
        logDto.setUserAgent(authentication.getName());
        logDto.setCreateBy(authentication.getName());
        logDto.setLogType(4);
        // 设置对应的token
        WebUtils.getRequest().ifPresent(request -> {
            logDto.setRemoteAddr(ServletUtil.getClientIP(request));
            logDto.setRequestUri(request.getRequestURI());
            logDto.setMethod(request.getMethod());
            logDto.setParamsData(request.getHeader(HttpHeaders.AUTHORIZATION));
        });
        LogServiceApi logServiceApi = SpringUtil.getBean(LogServiceApi.class);
        logServiceApi.add(logDto);
    }
}
